package com.example.service;

import com.example.annotation.Cache;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * 计算器服务
 * 演示IoC和AOP的使用
 */
@Service
public class CalculatorService {
    
    private static final Logger logger = LoggerFactory.getLogger(CalculatorService.class);
    
    /**
     * 加法运算 - 使用缓存注解
     */
    @Cache(expire = 30, prefix = "add")
    public double add(double a, double b) {
        logger.info("执行加法运算: {} + {}", a, b);
        // 模拟计算延迟
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return a + b;
    }
    
    /**
     * 减法运算 - 使用缓存注解
     */
    @Cache(expire = 30, prefix = "sub")
    public double subtract(double a, double b) {
        logger.info("执行减法运算: {} - {}", a, b);
        // 模拟计算延迟
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return a - b;
    }
    
    /**
     * 乘法运算 - 不使用缓存，演示日志切面
     */
    public double multiply(double a, double b) {
        logger.info("执行乘法运算: {} * {}", a, b);
        // 模拟计算延迟
        try {
            Thread.sleep(150);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return a * b;
    }
    
    /**
     * 除法运算 - 演示异常处理
     */
    public double divide(double a, double b) {
        logger.info("执行除法运算: {} / {}", a, b);
        
        if (b == 0) {
            throw new ArithmeticException("除数不能为零");
        }
        
        // 模拟计算延迟
        try {
            Thread.sleep(120);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        
        return a / b;
    }
    
    /**
     * 幂运算 - 使用缓存注解
     */
    @Cache(expire = 60, prefix = "power")
    public double power(double base, double exponent) {
        logger.info("执行幂运算: {} ^ {}", base, exponent);
        // 模拟计算延迟
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return Math.pow(base, exponent);
    }
    
    /**
     * 阶乘运算 - 使用缓存注解
     */
    @Cache(expire = 120, prefix = "factorial")
    public long factorial(int n) {
        logger.info("执行阶乘运算: {}!", n);
        
        if (n < 0) {
            throw new IllegalArgumentException("阶乘不能计算负数");
        }
        
        if (n == 0 || n == 1) {
            return 1;
        }
        
        // 模拟计算延迟
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        
        long result = 1;
        for (int i = 2; i <= n; i++) {
            result *= i;
        }
        
        return result;
    }
}
